package jvlite.authority;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import jvlite.core.JLiteContext;
import jvlite.ioc.BeanFactory;
import jvlite.mvc.annotaion.ClzAuth;
import jvlite.mvc.annotaion.MethodAuth;
import jvlite.util.LogUtil;
import myJlite.service.AuthService;

public class AuthLoader implements Callable<Boolean> {

	private void organizeAuth() {
		for (Class<?> cc : JLiteContext.clazzSet) {
			Map<String, Object> needAuthMap = new HashMap<String, Object>();
			if (cc.isAnnotationPresent(ClzAuth.class)) {
				ClzAuth clzAuth = cc.getAnnotation(ClzAuth.class);
				needAuthMap.put("ClzAuth", clzAuth.requirePower());
			} else {
				needAuthMap.put("ClzAuth", null);
			}
			Map<String, Object> needMtdAuthMap = new HashMap<String, Object>();
			Method[] declaredMethods = cc.getDeclaredMethods();
			for (Method method : declaredMethods) {

				if (method.isAnnotationPresent(MethodAuth.class)) {
					MethodAuth methodAuth = method
							.getAnnotation(MethodAuth.class);
					String[] requirePower = methodAuth.requirePower();
					needMtdAuthMap.put(method.getName(), requirePower);
				} else {
					needMtdAuthMap.put(method.getName(), null);
				}
				needAuthMap.put("MtdAuth", needMtdAuthMap);
			}
			BeanFactory.getAuthMap().put(cc.getName(), needAuthMap);
		}
		// initial AuthManager
		if (null == JLiteContext.authManager) {
			AbstractAuthManager defaultAuthManager = new DefaultAuthManager();
			defaultAuthManager.setAuthDataSource(new AuthDataSource());
			JLiteContext.authManager = defaultAuthManager;
		}
	}

	public void configAuth() {
		AuthService authService = (AuthService) BeanFactory.getBeanByClz(AuthService.class);
		if (null == authService) {
			LogUtil.info("authsetvice is null");
		} else {
			try {
				JLiteContext.authManager.getAuthDataSource().setHasAuthDS(
						authService
								.readAuth(JLiteContext.curUser));
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Boolean call() throws Exception {
		this.organizeAuth();
		// this.configAuth();
		return true;
	}

}
